<?php
/**
 * JSON数据库操作类
 * 提供JSON文件的增删改查功能
 */

class Database {
    private $dataDir;
    
    public function __construct() {
        $this->dataDir = DATA_DIR;
        $this->initializeData();
    }
    
    /**
     * 初始化数据文件
     */
    private function initializeData() {
        $files = [
            'categories.json' => [
                [
                    'id' => 1,
                    'name' => '常用网站',
                    'icon' => 'fas fa-star',
                    'sort' => 1,
                    'created_at' => date('Y-m-d H:i:s')
                ],
                [
                    'id' => 2,
                    'name' => '开发工具',
                    'icon' => 'fas fa-code',
                    'sort' => 2,
                    'created_at' => date('Y-m-d H:i:s')
                ]
            ],
            'navigations.json' => [
                [
                    'id' => 1,
                    'category_id' => 1,
                    'name' => '百度',
                    'url' => 'https://www.baidu.com',
                    'icon' => 'https://www.baidu.com/favicon.ico',
                    'icon_type' => 'url',
                    'description' => '百度搜索',
                    'sort' => 1,
                    'clicks' => 0,
                    'created_at' => date('Y-m-d H:i:s'),
                    'tag_ids' => []
                ],
                [
                    'id' => 2,
                    'category_id' => 2,
                    'name' => 'GitHub',
                    'url' => 'https://github.com',
                    'icon' => 'fab fa-github',
                    'icon_type' => 'class',
                    'description' => '代码托管平台',
                    'sort' => 1,
                    'clicks' => 0,
                    'created_at' => date('Y-m-d H:i:s'),
                    'tag_ids' => []
                ]
            ],
            'stats.json' => [
                'total_visits' => 0,
                'daily_visits' => [],
                'total_search_count' => 0,
                'daily_searches' => [],
                'search_keywords' => [],
                'last_updated' => date('Y-m-d H:i:s')
            ],
            'tags.json' => [
                [
                    'id' => 1,
                    'category_id' => 1,
                    'name_en' => 'popular',
                    'name_cn' => '热门',
                    'sort' => 1,
                    'created_at' => date('Y-m-d H:i:s')
                ],
                [
                    'id' => 2,
                    'category_id' => 1,
                    'name_en' => 'tools',
                    'name_cn' => '工具',
                    'sort' => 2,
                    'created_at' => date('Y-m-d H:i:s')
                ],
                [
                    'id' => 3,
                    'category_id' => 2,
                    'name_en' => 'frontend',
                    'name_cn' => '前端开发',
                    'sort' => 1,
                    'created_at' => date('Y-m-d H:i:s')
                ],
                [
                    'id' => 4,
                    'category_id' => 2,
                    'name_en' => 'backend',
                    'name_cn' => '后端开发',
                    'sort' => 2,
                    'created_at' => date('Y-m-d H:i:s')
                ]
            ],
            'settings.json' => [
                'admin_username' => ADMIN_USERNAME,
                'admin_password' => ADMIN_PASSWORD,
                'site_title' => SITE_TITLE,
                'site_description' => SITE_DESCRIPTION,
                'site_keywords' => SITE_KEYWORDS,
                'favicon_path' => 'assets/images/favicon.ico',
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]
        ];
        
        foreach ($files as $filename => $defaultData) {
            $filepath = $this->dataDir . '/' . $filename;
            if (!file_exists($filepath)) {
                $this->writeJson($filename, $defaultData);
            }
        }
    }
    
    /**
     * 读取JSON文件
     * @param string $filename 文件名
     * @return array 数据数组
     */
    public function readJson($filename) {
        $filepath = $this->dataDir . '/' . $filename;
        if (!file_exists($filepath)) {
            return [];
        }
        
        $content = file_get_contents($filepath);
        $data = json_decode($content, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            writeLog("JSON解析错误: " . json_last_error_msg() . " in file: $filename", 'ERROR');
            return [];
        }
        
        return $data ?: [];
    }
    
    /**
     * 写入JSON文件
     * @param string $filename 文件名
     * @param array $data 数据
     * @return bool 是否成功
     */
    public function writeJson($filename, $data) {
        $filepath = $this->dataDir . '/' . $filename;
        $jsonData = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            writeLog("JSON编码错误: " . json_last_error_msg(), 'ERROR');
            return false;
        }
        
        $result = file_put_contents($filepath, $jsonData, LOCK_EX);
        return $result !== false;
    }
    
    /**
     * 获取所有分类
     * @return array 分类列表
     */
    public function getCategories() {
        $categories = $this->readJson('categories.json');
        usort($categories, function($a, $b) {
            return ($a['sort'] ?? 0) - ($b['sort'] ?? 0); // 升序排列：排序值越小越靠前
        });
        return $categories;
    }
    
    /**
     * 根据ID获取分类
     * @param int $id 分类ID
     * @return array|null 分类信息
     */
    public function getCategoryById($id) {
        $categories = $this->getCategories();
        foreach ($categories as $category) {
            if ($category['id'] == $id) {
                return $category;
            }
        }
        return null;
    }
    
    /**
     * 添加分类
     * @param array $data 分类数据
     * @return bool 是否成功
     */
    public function addCategory($data) {
        $categories = $this->readJson('categories.json');
        $data['id'] = $this->getNextId($categories);
        $data['created_at'] = date('Y-m-d H:i:s');
        $categories[] = $data;
        return $this->writeJson('categories.json', $categories);
    }
    
    /**
     * 更新分类
     * @param int $id 分类ID
     * @param array $data 更新数据
     * @return bool 是否成功
     */
    public function updateCategory($id, $data) {
        $categories = $this->readJson('categories.json');
        foreach ($categories as &$category) {
            if ($category['id'] == $id) {
                // 如果更新了图标，检查是否需要删除旧的图标文件
                if (isset($data['icon'])) {
                    // 获取旧图标信息
                    $oldIcon = $category['icon'] ?? '';
                    $newIcon = $data['icon'];
                    
                    // 如果旧图标是上传的文件且新图标不同，删除旧文件
                    if (!empty($oldIcon) && 
                        $oldIcon !== $newIcon && 
                        strpos($oldIcon, 'uploads/icons/') !== false) {
                        
                        writeLog("准备删除分类旧图标文件: $oldIcon", 'INFO');
                        $this->deleteIconFile($oldIcon);
                    }
                }
                
                $category = array_merge($category, $data);
                $category['updated_at'] = date('Y-m-d H:i:s');
                return $this->writeJson('categories.json', $categories);
            }
        }
        return false;
    }
    
    /**
     * 删除本地上传的图标文件
     * @param string $iconUrl 图标URL或路径
     * @return bool 是否成功删除
     */
    private function deleteIconFile($iconUrl) {
        if (empty($iconUrl)) {
            writeLog("图标URL为空，跳过删除", 'INFO');
            return true;
        }
        
        // 检查是否是本地上传的文件（包含uploads/icons/）
        if (strpos($iconUrl, 'uploads/icons/') !== false) {
            // 提取文件名，支持完整URL和相对路径
            $filename = basename($iconUrl);
            $filePath = ICON_DIR . '/' . $filename;
            
            writeLog("尝试删除图标文件: $filePath", 'INFO');
            
            if (file_exists($filePath)) {
                $result = unlink($filePath);
                if ($result) {
                    writeLog("成功删除图标文件: $filePath", 'INFO');
                } else {
                    writeLog("删除图标文件失败: $filePath", 'ERROR');
                }
                return $result;
            } else {
                writeLog("图标文件不存在: $filePath", 'WARNING');
            }
        } else {
            writeLog("非本地上传文件，跳过删除: $iconUrl", 'INFO');
        }
        
        return true; // 非本地文件或文件不存在，返回true
    }

    /**
     * 删除分类
     * @param int $id 分类ID
     * @return bool 是否成功
     */
    public function deleteCategory($id) {
        // 获取要删除的分类信息
        $category = $this->getCategoryById($id);
        if (!$category) {
            return false;
        }
        
        // 获取该分类下的所有导航
        $navigations = $this->getNavigations($id);
        
        // 删除该分类下所有导航的图标文件
        foreach ($navigations as $nav) {
            if (isset($nav['icon']) && $nav['icon_type'] === 'url') {
                $this->deleteIconFile($nav['icon']);
            }
        }
        
        // 删除分类的图标文件（如果是上传的）
        if (isset($category['icon']) && strpos($category['icon'], 'uploads/icons/') !== false) {
            $this->deleteIconFile($category['icon']);
        }
        
        // 删除分类数据
        $categories = $this->readJson('categories.json');
        $categories = array_filter($categories, function($cat) use ($id) {
            return $cat['id'] != $id;
        });
        
        // 删除该分类下的所有导航数据
        $allNavigations = $this->readJson('navigations.json');
        $allNavigations = array_filter($allNavigations, function($nav) use ($id) {
            return $nav['category_id'] != $id;
        });
        $this->writeJson('navigations.json', array_values($allNavigations));
        
        return $this->writeJson('categories.json', array_values($categories));
    }
    
    /**
     * 获取所有导航
     * @param mixed $categoryId 分类ID，可以是单个ID或ID数组，null表示获取所有
     * @return array 导航列表
     */
    public function getNavigations($categoryId = null, $limit = null, $offset = 0) {
        $navigations = $this->readJson('navigations.json');

        if ($categoryId !== null) {
            $navigations = array_filter($navigations, function($nav) use ($categoryId) {
                // 兼容旧版单分类和新版多分类
                $navCategories = $this->getNavigationCategories($nav);

                if (is_array($categoryId)) {
                    // 检查导航是否属于指定的任一分类
                    return !empty(array_intersect($navCategories, $categoryId));
                } else {
                    // 检查导航是否属于指定分类
                    return in_array($categoryId, $navCategories);
                }
            });
        }

        usort($navigations, function($a, $b) {
            return ($a['sort'] ?? 0) - ($b['sort'] ?? 0); // 升序排列：排序值越小越靠前
        });

        // 应用分页
        if ($limit !== null) {
            $navigations = array_slice($navigations, $offset, $limit);
        }

        return array_values($navigations);
    }

    /**
     * 获取导航总数
     * @param mixed $categoryId 分类ID，可以是单个ID或ID数组，null表示获取所有
     * @return int 导航总数
     */
    public function getNavigationsCount($categoryId = null) {
        $navigations = $this->readJson('navigations.json');

        if ($categoryId !== null) {
            $navigations = array_filter($navigations, function($nav) use ($categoryId) {
                // 兼容旧版单分类和新版多分类
                $navCategories = $this->getNavigationCategories($nav);

                if (is_array($categoryId)) {
                    // 检查导航是否属于指定的任一分类
                    return !empty(array_intersect($navCategories, $categoryId));
                } else {
                    // 检查导航是否属于指定分类
                    return in_array($categoryId, $navCategories);
                }
            });
        }

        return count($navigations);
    }

    /**
     * 获取导航所属的分类ID数组
     * @param array $navigation 导航数据
     * @return array 分类ID数组
     */
    private function getNavigationCategories($navigation) {
        // 新版本：支持多分类
        if (isset($navigation['category_ids']) && is_array($navigation['category_ids'])) {
            return $navigation['category_ids'];
        }
        // 旧版本兼容：单分类
        elseif (isset($navigation['category_id'])) {
            return [$navigation['category_id']];
        }
        
        return [];
    }
    
    /**
     * 设置导航的分类
     * @param array &$navigation 导航数据引用
     * @param mixed $categoryIds 分类ID，可以是单个ID或ID数组
     */
    private function setNavigationCategories(&$navigation, $categoryIds) {
        if (is_array($categoryIds)) {
            $navigation['category_ids'] = array_map('intval', array_unique($categoryIds));
        } else {
            $navigation['category_ids'] = [intval($categoryIds)];
        }
        
        // 为了兼容旧版本，保留第一个分类作为主分类
        $navigation['category_id'] = $navigation['category_ids'][0] ?? 1;
    }

    /**
     * 根据ID获取导航
     * @param int $id 导航ID
     * @return array|null 导航信息
     */
    public function getNavigationById($id) {
        $navigations = $this->getNavigations();
        foreach ($navigations as $nav) {
            if ($nav['id'] == $id) {
                return $nav;
            }
        }
        return null;
    }
    
    /**
     * 添加导航
     * @param array $data 导航数据
     * @return bool 是否成功
     */
    public function addNavigation($data) {
        $navigations = $this->readJson('navigations.json');
        $data['id'] = $this->getNextId($navigations);
        $data['clicks'] = 0;
        $data['is_favorite'] = isset($data['is_favorite']) ? (int)$data['is_favorite'] : 0;
        $data['created_at'] = date('Y-m-d H:i:s');

        // 处理分类数据
        if (isset($data['category_ids'])) {
            $this->setNavigationCategories($data, $data['category_ids']);
        } elseif (isset($data['category_id'])) {
            $this->setNavigationCategories($data, $data['category_id']);
        }

        // 处理标签数据
        if (isset($data['tag_ids'])) {
            // 验证标签ID是否属于对应的分类
            $validTagIds = $this->validateNavigationTags($data['tag_ids'], $data['category_ids'] ?? [$data['category_id']]);
            $data['tag_ids'] = $validTagIds;
        } else {
            $data['tag_ids'] = [];
        }

        $navigations[] = $data;
        return $this->writeJson('navigations.json', $navigations);
    }
    
    /**
     * 更新导航
     * @param int $id 导航ID
     * @param array $data 更新数据
     * @return bool 是否成功
     */
    public function updateNavigation($id, $data) {
        $navigations = $this->readJson('navigations.json');
        foreach ($navigations as &$nav) {
            if ($nav['id'] == $id) {
                // 如果更新了图标，检查是否需要删除旧的图标文件
                if (isset($data['icon'])) {
                    // 获取旧图标信息
                    $oldIcon = $nav['icon'] ?? '';
                    $oldIconType = $nav['icon_type'] ?? 'class';
                    $newIcon = $data['icon'];
                    $newIconType = $data['icon_type'] ?? 'url';
                    
                    // 如果旧图标是上传的文件且新图标不同，删除旧文件
                    if (!empty($oldIcon) && 
                        $oldIconType === 'url' && 
                        $oldIcon !== $newIcon && 
                        strpos($oldIcon, 'uploads/icons/') !== false) {
                        
                        writeLog("准备删除旧图标文件: $oldIcon", 'INFO');
                        $this->deleteIconFile($oldIcon);
                    }
                }
                
                // 处理分类数据
                if (isset($data['category_ids'])) {
                    $this->setNavigationCategories($data, $data['category_ids']);
                } elseif (isset($data['category_id'])) {
                    $this->setNavigationCategories($data, $data['category_id']);
                }

                // 处理标签数据
                if (isset($data['tag_ids'])) {
                    // 验证标签ID是否属于对应的分类
                    $validTagIds = $this->validateNavigationTags($data['tag_ids'], $data['category_ids'] ?? [$data['category_id']]);
                    $data['tag_ids'] = $validTagIds;
                } else {
                    $data['tag_ids'] = [];
                }

                $nav = array_merge($nav, $data);
                $nav['updated_at'] = date('Y-m-d H:i:s');
                return $this->writeJson('navigations.json', $navigations);
            }
        }
        return false;
    }
    
    /**
     * 获取某个分类下的导航数量
     * @param int $categoryId 分类ID
     * @return int 导航数量
     */
    public function getNavigationCountByCategory($categoryId) {
        $navigations = $this->getNavigations($categoryId);
        return count($navigations);
    }
    
    /**
     * 获取导航的所有分类信息
     * @param int $navigationId 导航ID
     * @return array 分类信息数组
     */
    public function getNavigationCategoriesInfo($navigationId) {
        $navigation = $this->getNavigationById($navigationId);
        if (!$navigation) {
            return [];
        }
        
        $categoryIds = $this->getNavigationCategories($navigation);
        $categories = $this->getCategories();
        
        $result = [];
        foreach ($categories as $category) {
            if (in_array($category['id'], $categoryIds)) {
                $result[] = $category;
            }
        }
        
        return $result;
    }
    
    /**
     * 删除导航
     * @param int $id 导航ID
     * @return bool 是否成功
     */
    public function deleteNavigation($id) {
        // 获取要删除的导航信息
        $navigation = $this->getNavigationById($id);
        if (!$navigation) {
            return false;
        }
        
        // 删除导航的图标文件（如果是上传的）
        if (isset($navigation['icon']) && $navigation['icon_type'] === 'url') {
            $this->deleteIconFile($navigation['icon']);
        }
        
        // 删除导航数据
        $navigations = $this->readJson('navigations.json');
        $navigations = array_filter($navigations, function($nav) use ($id) {
            return $nav['id'] != $id;
        });
        return $this->writeJson('navigations.json', array_values($navigations));
    }
    
    /**
     * 增加点击次数
     * @param int $id 导航ID
     * @return bool 是否成功
     */
    public function incrementClicks($id) {
        $navigations = $this->readJson('navigations.json');
        foreach ($navigations as &$nav) {
            if ($nav['id'] == $id) {
                $nav['clicks'] = isset($nav['clicks']) ? $nav['clicks'] + 1 : 1;
                return $this->writeJson('navigations.json', $navigations);
            }
        }
        return false;
    }
    
    /**
     * 获取常用导航
     * @param int $limit 限制数量，默认获取所有
     * @return array 常用导航列表
     */
    public function getFavoriteNavigations($limit = 0) {
        $navigations = $this->readJson('navigations.json');
        
        // 过滤出常用导航
        $favorites = array_filter($navigations, function($nav) {
            return isset($nav['is_favorite']) && $nav['is_favorite'] == 1;
        });
        
        // 按排序值排序（与其他导航保持一致）
        usort($favorites, function($a, $b) {
            return ($a['sort'] ?? 0) - ($b['sort'] ?? 0); // 升序排列：排序值越小越靠前
        });
        
        // 限制数量
        if ($limit > 0) {
            $favorites = array_slice($favorites, 0, $limit);
        }
        
        return array_values($favorites);
    }
    
    /**
     * 设置导航为常用/取消常用
     * @param int $id 导航ID
     * @param bool $isFavorite 是否为常用
     * @return bool 是否成功
     */
    public function setNavigationFavorite($id, $isFavorite) {
        $navigations = $this->readJson('navigations.json');
        foreach ($navigations as &$nav) {
            if ($nav['id'] == $id) {
                $nav['is_favorite'] = $isFavorite ? 1 : 0;
                $nav['updated_at'] = date('Y-m-d H:i:s');
                return $this->writeJson('navigations.json', $navigations);
            }
        }
        return false;
    }
    
    /**
     * 获取统计信息
     * @return array 统计数据
     */
    public function getStats() {
        return $this->readJson('stats.json');
    }
    
    /**
     * 更新统计信息
     * @param array $data 统计数据
     * @return bool 是否成功
     */
    public function updateStats($data) {
        $stats = $this->getStats();
        $stats = array_merge($stats, $data);
        $stats['last_updated'] = date('Y-m-d H:i:s');
        return $this->writeJson('stats.json', $stats);
    }
    
    /**
     * 增加搜索次数
     * @param string $query 搜索关键词
     * @param string $engine 搜索引擎
     * @return bool 是否成功
     */
    public function incrementSearchCount($query, $engine = 'baidu') {
        $stats = $this->readJson('stats.json');
        $today = date('Y-m-d');
        $currentTime = date('Y-m-d H:i:s');
        
        // 初始化统计数据（如果是首次搜索）
        if (empty($stats)) {
            $stats = [
                'total_visits' => 0,
                'today_visits' => 0,
                'last_visit_date' => '',
                'total_searches' => 0,
                'search_count' => 0,
                'total_search_count' => 0,
                'search_keywords' => [],
                'daily_visits' => [],
                'daily_searches' => [],
                'daily_stats' => [],
                'popular_links' => [],
                'monthly_stats' => [],
                'yearly_stats' => [],
                'browser_stats' => [],
                'system_stats' => [],
                'last_updated' => $currentTime,
                'created_at' => $currentTime
            ];
        }
        
        // 初始化搜索关键词数组（如果不存在）
        if (!isset($stats['search_keywords']) || !is_array($stats['search_keywords'])) {
            $stats['search_keywords'] = [];
        }
        
        // 初始化每日搜索量数组（如果不存在）
        if (!isset($stats['daily_searches']) || !is_array($stats['daily_searches'])) {
            $stats['daily_searches'] = [];
        }
        
        // 查找是否已存在该关键词和搜索引擎组合
        $keywordExists = false;
        $keywordIndex = -1;
        
        foreach ($stats['search_keywords'] as $index => $item) {
            if (isset($item['keyword']) && $item['keyword'] === $query) {
                // 如果记录有engine字段，则必须匹配engine
                if (isset($item['engine']) && $item['engine'] === $engine) {
                    $keywordExists = true;
                    $keywordIndex = $index;
                    break;
                }
                // 如果记录没有engine字段，也将其视为匹配，并在更新时添加engine字段
                else if (!isset($item['engine']) && $engine === 'baidu') {
                    $keywordExists = true;
                    $keywordIndex = $index;
                    break;
                }
            }
        }
        
        // 更新或添加搜索关键词
        if ($keywordExists && $keywordIndex !== -1) {
            // 更新已存在的关键词
            $stats['search_keywords'][$keywordIndex]['count'] = isset($stats['search_keywords'][$keywordIndex]['count']) ? $stats['search_keywords'][$keywordIndex]['count'] + 1 : 2;
            $stats['search_keywords'][$keywordIndex]['last_searched'] = $currentTime;
            // 确保engine字段存在
            if (!isset($stats['search_keywords'][$keywordIndex]['engine'])) {
                $stats['search_keywords'][$keywordIndex]['engine'] = $engine;
            }
        } else {
            // 添加新的关键词和搜索引擎组合
            $stats['search_keywords'][] = [
                'keyword' => $query,
                'count' => 1,
                'first_searched' => $currentTime,
                'last_searched' => $currentTime,
                'engine' => $engine // 保存搜索引擎信息
            ];
        }
        
        // 增加总搜索次数
        $stats['total_searches'] = isset($stats['total_searches']) ? $stats['total_searches'] + 1 : 1;
        $stats['total_search_count'] = $stats['total_searches']; // 保持兼容
        $stats['search_count'] = $stats['total_searches']; // 保持兼容
        
        // 增加今日搜索量
        $stats['daily_searches'][$today] = isset($stats['daily_searches'][$today]) ? $stats['daily_searches'][$today] + 1 : 1;
        
        // 更新最后更新时间
        $stats['last_updated'] = $currentTime;
        
        return $this->writeJson('stats.json', $stats);
    }
    
    /**
     * 增加访问量
     * @return bool 是否成功
     */
    public function incrementVisits() {
        $stats = $this->readJson('stats.json');
        $today = date('Y-m-d');
        
        // 初始化统计数据（如果是首次访问）
        if (empty($stats)) {
            $stats = [
                'total_visits' => 0,
                'today_visits' => 0,
                'last_visit_date' => $today,
                'total_searches' => 0,
                'search_count' => 0,
                'total_search_count' => 0,
                'search_keywords' => [],
                'daily_visits' => [],
                'daily_searches' => [],
                'daily_stats' => [],
                'popular_links' => [],
                'monthly_stats' => [],
                'yearly_stats' => [],
                'browser_stats' => [],
                'system_stats' => [],
                'last_updated' => date('Y-m-d H:i:s'),
                'created_at' => date('Y-m-d H:i:s')
            ];
        }
        
        // 增加总访问量
        $stats['total_visits'] = isset($stats['total_visits']) ? $stats['total_visits'] + 1 : 1;
        
        // 初始化每日访问量数组（如果不存在）
        if (!isset($stats['daily_visits']) || !is_array($stats['daily_visits'])) {
            $stats['daily_visits'] = [];
        }
        
        // 增加今日访问量
        $stats['daily_visits'][$today] = isset($stats['daily_visits'][$today]) ? $stats['daily_visits'][$today] + 1 : 1;
        
        // 更新今日访问量字段
        $stats['today_visits'] = $stats['daily_visits'][$today];
        
        // 更新最后访问日期
        $stats['last_visit_date'] = $today;
        
        // 更新最后更新时间
        $stats['last_updated'] = date('Y-m-d H:i:s');
        
        return $this->writeJson('stats.json', $stats);
    }
    
    /**
     * 重置统计信息
     * @return bool 是否成功
     */
    public function resetStats() {
        // 获取当前统计数据以保留不需要重置的字段
        $currentStats = $this->readJson('stats.json');
        
        // 重置所有统计相关字段
        $resetStats = [
            'total_visits' => 0,
            'today_visits' => 0,
            'last_visit_date' => '',
            'total_searches' => 0,
            'search_count' => 0,
            'total_search_count' => 0,
            'search_keywords' => [],
            'daily_visits' => [],
            'daily_searches' => [],
            'daily_stats' => [],
            'popular_links' => [],
            'monthly_stats' => [],
            'yearly_stats' => [],
            'browser_stats' => [],
            'system_stats' => [],
            'last_updated' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            // 保留创建时间
            'created_at' => $currentStats['created_at'] ?? date('Y-m-d H:i:s')
        ];
        
        return $this->writeJson('stats.json', $resetStats);
    }
    
    /**
     * 获取热门搜索关键词
     * @param int $limit 返回数量
     * @return array 热门关键词列表
     */
    public function getPopularKeywords($limit = 10) {
        $stats = $this->getStats();
        
        if (!isset($stats['search_keywords']) || empty($stats['search_keywords'])) {
            return [];
        }
        
        $keywords = $stats['search_keywords'];
        arsort($keywords);
        
        return array_slice($keywords, 0, $limit, true);
    }
    
    /**
     * 获取最新搜索关键词（按last_searched排序）
     * @param int $limit 返回数量
     * @return array 最新搜索关键词列表
     */
    public function getRecentKeywords($limit = 20) {
        $stats = $this->getStats();
        
        if (!isset($stats['search_keywords']) || empty($stats['search_keywords'])) {
            return [];
        }
        
        $keywords = $stats['search_keywords'];
        
        // 确保keywords是数组
        if (!is_array($keywords)) {
            return [];
        }
        
        // 转换为模板所需的结构
        $formattedKeywords = [];
        
        // 检查search_keywords是普通数组还是关联数组
        if (isset($keywords[0]) && is_array($keywords[0]) && isset($keywords[0]['keyword'])) {
            // 普通数组格式：每个元素是包含keyword字段的对象
            foreach ($keywords as $info) {
                $formattedKeywords[] = [
                    'keyword' => $info['keyword'] ?? '',
                    'count' => $info['count'] ?? 1,
                    'last_searched' => $info['last_searched'] ?? date('Y-m-d H:i:s'),
                    'engine' => $info['engine'] ?? 'baidu' // 包含搜索引擎信息
                ];
            }
        } else {
            // 关联数组格式：键是关键词，值是包含count和last_searched的对象
            foreach ($keywords as $keyword => $info) {
                $formattedKeywords[] = [
                    'keyword' => $keyword,
                    'count' => $info['count'] ?? 1,
                    'last_searched' => $info['last_searched'] ?? date('Y-m-d H:i:s'),
                    'engine' => $info['engine'] ?? 'baidu' // 包含搜索引擎信息
                ];
            }
        }
        
        // 按last_searched倒序排序（最新搜索的在前）
        usort($formattedKeywords, function($a, $b) {
            return strtotime($b['last_searched']) - strtotime($a['last_searched']);
        });
        
        return array_slice($formattedKeywords, 0, $limit);
    }
    
    /**
     * 获取下一个ID
     * @param array $data 数据数组
     * @return int 下一个ID
     */
    private function getNextId($data) {
        if (empty($data)) {
            return 1;
        }
        
        $maxId = max(array_column($data, 'id'));
        return $maxId + 1;
    }
    
    /**
     * 获取系统设置
     * @return array 系统设置
     */
    public function getSettings() {
        return $this->readJson('settings.json');
    }
    
    /**
     * 更新系统设置
     * @param array $data 设置数据
     * @return bool 是否成功
     */
    public function updateSettings($data) {
        $settings = $this->getSettings();
        $settings = array_merge($settings, $data);
        $settings['updated_at'] = date('Y-m-d H:i:s');
        return $this->writeJson('settings.json', $settings);
    }
    
    /**
     * 更新管理员密码
     * @param string $newPassword 新密码
     * @return bool 是否成功
     */
    public function updateAdminPassword($newPassword) {
        return $this->updateSettings(['admin_password' => $newPassword]);
    }
    
    /**
     * 更新网站信息
     * @param array $data 网站信息
     * @return bool 是否成功
     */
    public function updateSiteInfo($data) {
        $allowedFields = [
            'site_title', 
            'site_description', 
            'site_keywords', 
            'favicon_path',
            'favicon_link',
            'footer_copyright',
            'footer_icp_number',
            'footer_beian_number',
            'footer_other_info',
            'footer_script_code'
        ];
        $updateData = array_intersect_key($data, array_flip($allowedFields));
        return $this->updateSettings($updateData);
    }
    
    /**
     * 验证管理员密码
     * @param string $password 密码
     * @return bool 是否正确
     */
    public function validateAdminPassword($password) {
        $settings = $this->getSettings();
        return isset($settings['admin_password']) && $settings['admin_password'] === $password;
    }

    // ==================== 标签管理方法 ====================

    /**
     * 获取所有标签
     * @param int|null $categoryId 分类ID，为null则获取所有标签
     * @return array 标签列表
     */
    public function getTags($categoryId = null) {
        $tags = $this->readJson('tags.json');

        // 如果指定了分类ID，则筛选该分类下的标签
        if ($categoryId !== null) {
            $tags = array_filter($tags, function($tag) use ($categoryId) {
                return $tag['category_id'] == $categoryId;
            });
        }

        // 按排序字段排序
        usort($tags, function($a, $b) {
            return $a['sort'] - $b['sort'];
        });

        return $tags;
    }

    /**
     * 根据ID获取标签
     * @param int $id 标签ID
     * @return array|null 标签信息
     */
    public function getTagById($id) {
        $tags = $this->getTags();
        foreach ($tags as $tag) {
            if ($tag['id'] == $id) {
                return $tag;
            }
        }
        return null;
    }

    /**
     * 添加标签
     * @param array $data 标签数据
     * @return bool 是否成功
     */
    public function addTag($data) {
        $tags = $this->readJson('tags.json');

        // 验证分类ID是否存在
        if (!$this->getCategoryById($data['category_id'])) {
            return false;
        }

        // 验证英文名称在同级分类下唯一
        foreach ($tags as $tag) {
            if ($tag['category_id'] == $data['category_id'] && $tag['name_en'] == $data['name_en']) {
                return false;
            }
        }

        $data['id'] = $this->getNextId($tags);
        $data['created_at'] = date('Y-m-d H:i:s');
        $tags[] = $data;
        return $this->writeJson('tags.json', $tags);
    }

    /**
     * 更新标签
     * @param int $id 标签ID
     * @param array $data 更新数据
     * @return bool 是否成功
     */
    public function updateTag($id, $data) {
        $tags = $this->readJson('tags.json');

        // 验证分类ID是否存在
        if (isset($data['category_id']) && !$this->getCategoryById($data['category_id'])) {
            return false;
        }

        foreach ($tags as &$tag) {
            if ($tag['id'] == $id) {
                // 验证英文名称在同级分类下唯一（排除自身）
                if (isset($data['name_en'])) {
                    foreach ($tags as $otherTag) {
                        if ($otherTag['id'] != $id &&
                            $otherTag['category_id'] == ($data['category_id'] ?? $tag['category_id']) &&
                            $otherTag['name_en'] == $data['name_en']) {
                            return false;
                        }
                    }
                }

                $tag = array_merge($tag, $data);
                return $this->writeJson('tags.json', $tags);
            }
        }
        return false;
    }

    /**
     * 删除标签
     * @param int $id 标签ID
     * @return bool 是否成功
     */
    public function deleteTag($id) {
        $tags = $this->readJson('tags.json');
        $tags = array_filter($tags, function($tag) use ($id) {
            return $tag['id'] != $id;
        });
        return $this->writeJson('tags.json', array_values($tags));
    }

    /**
     * 获取分类下的标签数���
     * @param int $categoryId 分类ID
     * @return int 标签数量
     */
    public function getTagCountByCategory($categoryId) {
        $tags = $this->getTags($categoryId);
        return count($tags);
    }

    // ==================== 导航标签关联方法 ====================

    /**
     * 验证导航标签是否属于指定的分类
     * @param array $tagIds 标签ID数组
     * @param array $categoryIds 分类ID数组
     * @return array 有效的标签ID数组
     */
    public function validateNavigationTags($tagIds, $categoryIds) {
        if (empty($tagIds) || empty($categoryIds)) {
            return [];
        }

        $validTagIds = [];
        $allTags = $this->getTags();

        foreach ($tagIds as $tagId) {
            foreach ($allTags as $tag) {
                if ($tag['id'] == $tagId && in_array($tag['category_id'], $categoryIds)) {
                    $validTagIds[] = (int)$tagId;
                    break;
                }
            }
        }

        return array_unique($validTagIds);
    }

    /**
     * 获取导航的标签信息
     * @param int $navigationId 导航ID
     * @return array 标签信息数组
     */
    public function getNavigationTags($navigationId) {
        $navigation = $this->getNavigationById($navigationId);
        if (!$navigation || !isset($navigation['tag_ids'])) {
            return [];
        }

        $tagIds = $navigation['tag_ids'];
        if (empty($tagIds)) {
            return [];
        }

        $allTags = $this->getTags();
        $result = [];

        foreach ($allTags as $tag) {
            if (in_array($tag['id'], $tagIds)) {
                $result[] = $tag;
            }
        }

        return $result;
    }

    /**
     * 根据分类ID获取标签选项（用于下拉选择）
     * @param array $categoryIds 分类ID数组
     * @return array 标签选项数组
     */
    public function getTagOptionsByCategories($categoryIds) {
        if (empty($categoryIds)) {
            return [];
        }

        $allTags = $this->getTags();
        $options = [];

        foreach ($allTags as $tag) {
            if (in_array($tag['category_id'], $categoryIds)) {
                $options[] = [
                    'id' => $tag['id'],
                    'name_cn' => $tag['name_cn'],
                    'name_en' => $tag['name_en'],
                    'category_id' => $tag['category_id']
                ];
            }
        }

        return $options;
    }
}